package com.boarsoft.boar.sequence.length10;

import com.boarsoft.boar.sequence.snowflake.SnowflakeConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 *
 */
public class Length10Worker {

    private static final Logger log = LoggerFactory.getLogger(Length10Worker.class);

    private static final char[] CHARS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
    private static final int CHARS_LENGTH = CHARS.length;

    private static Long longId = null;

    private int workerId;

    public Length10Worker(SnowflakeConfig snowflakeConfig){
        if(snowflakeConfig.getWorkerId() > CHARS_LENGTH){
            log.error("workerId配置范围超限!");
        }
        this.workerId = snowflakeConfig.getWorkerId();
    }
    public String getLength10Id() {
        String workerId = String.valueOf(CHARS[this.workerId]);
        if (longId == null) {
            String dateStr = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
            dateStr = "1" + dateStr.substring(2);
            longId = Long.parseLong(dateStr);
        } else {
            longId = longId + 1;
        }
        return convert(longId) + workerId;
    }

    private static String convert(Long a) {
        StringBuilder sb = new StringBuilder();
        while (a > 0) {
            int i = (int) (a % CHARS_LENGTH);
            sb.append(CHARS[i]);
            a /= CHARS_LENGTH;
        }
        return sb.reverse().toString();
    }
}
